﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace MaxStoreErp.Core.Commands
{
    public abstract class RelayCommandBase : ICommand
    {
        readonly Predicate<object> _canExecute;
        readonly Action<object> _execute;

        protected RelayCommandBase(Action<object> execute, Predicate<object> canExecute = null)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }

            _execute = execute;
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }

            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }

    public class RelayCommand : RelayCommandBase
    {
        public RelayCommand(Action execute)
            : base(o => execute())
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
            : base(o => execute(), o => canExecute())
        {
        }

        public void Execute()
        {
            Execute(null);
        }

        public bool CanExecute()
        {
            return CanExecute(null);
        }
    }

    public class RelayCommand<T> : RelayCommandBase
    {
        public RelayCommand(Action<T> execute)
            : base(o => execute((T)o))
        {
        }

        public RelayCommand(Action<T> execute, Predicate<T> canExecute)
            : base(o => execute((T)o), o => canExecute((T)o))
        {
        }

        public void Execute(T parameter)
        {
            Execute((object)parameter);
        }

        public bool CanExecute(T parameter)
        {
            return CanExecute((object)parameter);
        }
    }
}
